const Router = require('koa-router')
const db = require('../db')
const cache = require('../middleware/cache')

const router = new Router({ prefix: '/api/course' })

// 课程详情接口使用缓存中间件，缓存时间60秒
router.get('/:id', cache({ 
  expire: 60,
  key: (ctx) => {
    const courseId = ctx.params.id;
    return `course:${courseId}`;
  }
}), async (ctx) => {
  try {
    const courseId = ctx.params.id

    // 查询课程基本信息
    const [course] = await db.query(`
      SELECT 
        c.*, t.name as teacher_name,
        t.avatar as teacher_avatar,
        t.title as teacher_title,
        t.description as teacher_description,
        (SELECT COUNT(*) FROM course_schedules WHERE course_id = c.id) as total_chapters
      FROM courses c
      LEFT JOIN teachers t ON c.teacher_id = t.id
      WHERE c.id = ?
    `, [courseId])

    if (!course) {
      ctx.status = 404
      ctx.body = { code: 404, message: '课程不存在' }
      return
    }

    // 查询课程章节
    const schedules = await db.query(`
      SELECT id, title, content, sort
      FROM course_schedules
      WHERE course_id = ?
      ORDER BY sort
    `, [courseId])

    // 查询课程评论
    const comments = await db.query(`
      SELECT 
        cc.*,
        u.nickname,
        u.avatar
      FROM course_comments cc
      INNER JOIN users u ON cc.user_id = u.id
      WHERE cc.course_id = ?
    `, [courseId])

    // 查询相似课程
    const similarCourses = await db.query(`
      SELECT 
        c.id, 
        c.title, 
        c.price, 
        c.image_url,
        c.enroll_count,
        c.tags
      FROM courses c
      WHERE c.category_id = (
        SELECT category_id 
        FROM courses 
        WHERE id = ?
      )
      AND c.id != ?
      ORDER BY c.enroll_count DESC
      LIMIT 3
    `, [courseId, courseId])

    const response = {
      code: 200,
      data: {
        ...course,
        schedules,
        comments: comments.map(comment => ({
          id: comment.id,
          content: comment.content,
          rating: comment.rating,
          created_at: comment.created_at,
          nickname: comment.nickname,
          avatar: comment.avatar
        })),
        similarCourses: similarCourses.map(course => ({
          id: course.id,
          title: course.title,
          price: course.price,
          imageUrl: course.image_url ? `${course.image_url}` : '',
          enrollCount: course.enroll_count,
          tags: course.tags ? course.tags.split(',') : []
        }))
      }
    }

    ctx.body = response;
  } catch (err) {
    console.error('获取课程详情失败:', err)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      error: err.message
    }
  }
})

// 批量获取课程详情接口
router.get('/batch', async (ctx) => {
  try {
    const { courseIds } = ctx.query;
    
    if (!courseIds) {
      ctx.status = 400;
      ctx.body = { code: 400, message: '缺少必要参数: courseIds' };
      return;
    }

    // 将字符串形式的ID转为数组
    const idArray = courseIds.split(',').map(id => parseInt(id, 10));
    
    // 检查是否有有效的ID
    if (idArray.length === 0) {
      ctx.status = 400;
      ctx.body = { code: 400, message: '无效的课程ID列表' };
      return;
    }

    // 生成占位符字符串 ?,?,?...
    const placeholders = idArray.map(() => '?').join(',');
    
    // 查询课程基本信息
    const courses = await db.query(`
      SELECT 
        c.*, t.name as teacher_name,
        t.avatar as teacher_avatar,
        t.title as teacher_title,
        t.description as teacher_description,
        (SELECT COUNT(*) FROM course_schedules WHERE course_id = c.id) as total_chapters
      FROM courses c
      LEFT JOIN teachers t ON c.teacher_id = t.id
      WHERE c.id IN (${placeholders})
    `, idArray);

    ctx.body = {
      code: 200,
      data: courses ? courses.map(course => ({
        id: course.id,
        title: course.title,
        price: course.price,
        image_url: course.image_url,
        enroll_count: course.enroll_count || 0,
        tags: course.tags ? course.tags.split(',') : [],
        teacher_name: course.teacher_name
      })) : []
    };
  } catch (err) {
    console.error('批量获取课程详情失败:', err);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      error: err.message
    };
  }
});

// 更新课程信息
router.put('/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const updateData = ctx.request.body;
    
    // 更新课程信息
    await db.query('UPDATE courses SET ? WHERE id = ?', [updateData, id]);
    
    // 使相关缓存失效
    await cache.invalidateCache(`course:${id}`);
    await cache.invalidateCache('api:cache:GET:/api/home*');
    
    console.log(`✅ 课程信息已更新: id=${id}`);
    ctx.body = { code: 200, message: '更新成功' };
  } catch (err) {
    console.error('更新课程信息失败:', err);
    ctx.status = 500;
    ctx.body = { code: 500, message: '服务器内部错误' };
  }
});

module.exports = router